package com.juno.cafenoa.mypage;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.juno.cafenoa.Constants;
import com.juno.cafenoa.R;
import com.juno.cafenoa.TopNavigatorView;
import com.juno.cafenoa.util.CafeNoaPreference;

/**
 * 패스워드 정의를 위한 activity
 * @author JUNHO
 */
public class PasswordActivity extends Activity implements OnClickListener {
	/**
	 * 비밀번호 숫자 4자리 나타내는 EditText.
	 */
	RelativeLayout[] etPassword = new RelativeLayout[4];
	ImageView[] maskPassword	= new ImageView[4];
	
	/**
	 * password숫자 0~9
	 */
	Button[] btnPassword = new Button[10];
	
	TextView text;
	//한자리 지우기 버튼
	Button btnBack;
	//패스워드설정 취소버튼.
	Button btnCancel;
	TopNavigatorView navi = null;

	int mode;
		
	/**
	 * 패스워드 1~4번째까지 입력된 상태인지 아닌지 나타내는 flag.
	 */
	private boolean firstChar = false;
	private boolean secondChar = false;
	private boolean thirdChar = false;
	private boolean fourthChar = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_password);
		
		navi = (TopNavigatorView) findViewById(R.id.navi_password);
		navi.init("패스워드 설정");
		
		mode = getIntent().getExtras().getInt(Constants.USER_PASSWORD_MODE_SET);
		
		text = (TextView) findViewById(R.id.passwordTitle);
		
		//비밀번호 설정을 위한 mode인지, 인증을 위한 mode인지 구별하기위함.
		if(mode==Constants.PASSWORD_RESET)
			text.setText("비밀번호 바꾸기");
		else if(mode==Constants.PASSWORD_SET_LONGIN)
			text.setText("비밀번호 인증");
				
		etPassword[0] = (RelativeLayout) findViewById(R.id.password_input1);
		etPassword[1] = (RelativeLayout) findViewById(R.id.password_input2);
		etPassword[2] = (RelativeLayout) findViewById(R.id.password_input3);
		etPassword[3] = (RelativeLayout) findViewById(R.id.password_input4);
		
		maskPassword[0] = (ImageView) findViewById(R.id.password_mask1);
		maskPassword[1] = (ImageView) findViewById(R.id.password_mask2);
		maskPassword[2] = (ImageView) findViewById(R.id.password_mask3);
		maskPassword[3] = (ImageView) findViewById(R.id.password_mask4);
		
		btnPassword[0] = (Button) findViewById(R.id.password_number0);
		btnPassword[1] = (Button) findViewById(R.id.password_number1);
		btnPassword[2] = (Button) findViewById(R.id.password_number2);
		btnPassword[3] = (Button) findViewById(R.id.password_number3);
		btnPassword[4] = (Button) findViewById(R.id.password_number4);
		btnPassword[5] = (Button) findViewById(R.id.password_number5);
		btnPassword[6] = (Button) findViewById(R.id.password_number6);
		btnPassword[7] = (Button) findViewById(R.id.password_number7);
		btnPassword[8] = (Button) findViewById(R.id.password_number8);
		btnPassword[9] = (Button) findViewById(R.id.password_number9);
		
		btnBack 	   = (Button) findViewById(R.id.password_number_back);
		btnCancel 	   = (Button) findViewById(R.id.password_number_cancel);
		
		btnPassword[0].setOnClickListener(this);
		btnPassword[1].setOnClickListener(this);
		btnPassword[2].setOnClickListener(this);
		btnPassword[3].setOnClickListener(this);
		btnPassword[4].setOnClickListener(this);
		btnPassword[5].setOnClickListener(this);
		btnPassword[6].setOnClickListener(this);
		btnPassword[7].setOnClickListener(this);
		btnPassword[8].setOnClickListener(this);
		btnPassword[9].setOnClickListener(this);
		btnBack.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		
	}
	@Override
	public void onClick(View v) {
		if(v == btnPassword[0]){
			inputNumber(0);
		}else if(v == btnPassword[1]){
			inputNumber(1);
		}else if(v == btnPassword[2]){
			inputNumber(2);
		}else if(v == btnPassword[3]){
			inputNumber(3);
		}else if(v == btnPassword[4]){
			inputNumber(4);
		}else if(v == btnPassword[5]){
			inputNumber(5);
		}else if(v == btnPassword[6]){
			inputNumber(6);
		}else if(v == btnPassword[7]){
			inputNumber(7);
		}else if(v == btnPassword[8]){
			inputNumber(8);
		}else if(v == btnPassword[9]){
			inputNumber(9);
		}else if(v==btnBack){
			backNumber();
		}else if(v==btnCancel){
			finish();
		}
	}
	private void backNumber(){
		if(fourthChar){
			maskPassword[3].setVisibility(View.GONE);
			temp[3] = -2;
			fourthChar = false;
			return;
		} 
		
		if(thirdChar){
			maskPassword[2].setVisibility(View.GONE);
			temp[2] = -2;
			thirdChar = false;
			return;
		} 
		if(secondChar){
			maskPassword[1].setVisibility(View.GONE);
			temp[1] = -2;
			secondChar = false;
			return;
		}
		if(firstChar){
			maskPassword[0].setVisibility(View.GONE);
			temp[0] = -2;
			firstChar = false;
		} else {
			finish();
		}
	}
	int[] temp = new int[4];
	
	/**
	 * 버튼으로 한자리씩 누를때 발생하는 이벤트
	 * 한자리 입력되었는지 flag를 통하여 판단후 다음자리 et를 입력함.
	 * @param num
	 */
	private void inputNumber(int num){
		if(!firstChar){
			maskPassword[0].setVisibility(View.VISIBLE);
			temp[0] = num;
			firstChar = true;
			return;
		}
		if(!secondChar && temp[0]>-1){
			maskPassword[1].setVisibility(View.VISIBLE);
			temp[1] = num;
			secondChar = true;
			return;
		}
		if(!thirdChar && temp[1]>-1){
			maskPassword[2].setVisibility(View.VISIBLE);
			temp[2] = num;
			thirdChar = true;
			return;
		} 
		if(!fourthChar && temp[2]>-1){
			maskPassword[3].setVisibility(View.VISIBLE);
			temp[3] = num;
			//4자리 모두 입력되었으면.
			//패스워드를 붙인 후
			//설정일경우 다음 인텐트로 넘기고
			//설정이 아닐경우 패스워드가 맞는지 안맞는지 판단하여 return.
			String password = "";
			for(int i=0;i<temp.length;i++)
				password += String.valueOf(temp[i]);
			Log.v("passwordk???","password : " + password);
			
			//mode : password_set(패스워드 최초설정), password_set_regedit(회원가입에 필요한 패스워드 설정)
			//       password_confirm(패스워드 맞는지 아닌지 확인.), password_reset(설정된 패스워드에서 변경)
			//       password_login(로그인액티비티에서 입력한 password 리턴받을시 이용.)
			
			try {
				Thread.sleep(100);
				if(mode==Constants.PASSWORD_SET){
					Intent intent = new Intent(this, PasswordConfirmActivity.class);
					intent.putExtra(Constants.USER_PASSWORD_STRING, password);
					intent.putExtra(Constants.USER_PASSWORD_MODE_SET, mode);
					startActivity(intent);
					finish();
				}else if(mode==Constants.PASSWORD_SET_REGEDIT){
					Intent intent = new Intent(this, PasswordConfirmActivity.class);
					intent.putExtra(Constants.USER_PASSWORD_MODE_SET, Constants.PASSWORD_SET_REGEDIT);
					intent.putExtra(Constants.USER_PASSWORD_STRING, password);
					startActivityForResult(intent, Constants.REQUEST_PASSWORD_REGEDIT);
				}else if(mode==Constants.PASSWORD_RESET){
					if(password.equalsIgnoreCase(CafeNoaPreference.getUserPassword(this))){
						Intent intent = new Intent(this, PasswordActivity.class);
						intent.putExtra(Constants.USER_PASSWORD_MODE_SET, Constants.PASSWORD_SET);
						startActivity(intent);
						finish();				
					} else {
						Toast.makeText(this, "잘못된 패스워드입니다", Toast.LENGTH_SHORT).show();
						for(int i=0;i<4;i++){
							maskPassword[i].setVisibility(View.GONE);
						}
						etPassword[0].requestFocus();
						firstChar = false;
						secondChar = false;
						thirdChar = false;
						fourthChar = false;
					}
				} else if(mode==Constants.PASSWORD_CONFIRM){
					if(password.equalsIgnoreCase(CafeNoaPreference.getUserPassword(this))){
						Toast.makeText(this, "패스워드 일치!", Toast.LENGTH_SHORT).show();
						Intent intent = new Intent();
						intent.putExtra(Constants.USER_PASSWORD_EQUAL, true);
						setResult(Constants.REQUEST_PASWORD_CONFIRM, intent);
						finish();
					} else {
						Toast.makeText(this, "잘못된 패스워드입니다", Toast.LENGTH_SHORT).show();
						for(int i=0;i<4;i++){
							maskPassword[i].setVisibility(View.GONE);
						}
						etPassword[0].requestFocus();
						firstChar = false;
						secondChar = false;
						thirdChar = false;
						fourthChar = false;
					}
					
				} else if(mode == Constants.PASSWORD_SET_LONGIN){
					Intent intent = new Intent();
					intent.putExtra(Constants.USER_PASSWORD_STRING, password);
					setResult(Constants.REQUEST_PASSWORD_SET, intent);
					finish();
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			//발생 x 만약의 오류를 위하여.
			Toast.makeText(this, "4자리가 모두 찼습니다.", Toast.LENGTH_SHORT).show();
		}
		
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==Constants.REQUEST_PASSWORD_REGEDIT){
			Intent intent = data;
			setResult(Constants.REQUEST_PASSWORD_REGEDIT, intent);
			finish();
		}
	}
}
